//
//  SLNetworkTools.swift
//  06-Swift-AFN 网络封装
//
//  Created by Apple on 16/10/23.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit
import AFNetworking
// get post 请求方式枚举(Swift 枚举写法)
enum SLNetworkToolsMethod: String {
    case get = "get"
    case post = "post"
}

class SLNetworkTools: AFHTTPSessionManager {
    // 全局访问点
    static let sharedTools: SLNetworkTools = {
        let tools = SLNetworkTools()
        // 反序列化格式
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    /// 网络请求公共方法
    ///
    /// - parameter method:     请求方式
    /// - parameter urlString:   url 地址
    /// - parameter parameters: 请求参数
    /// - parameter success:    成功
    /// - parameter failure:    失败
    func requet(method: SLNetworkToolsMethod, urlString: String, parameters: Any?, success:@escaping (Any?)->(), failure:@escaping (Error)->()){
        // 如果是 get 请求
        if method == .get {
            get(urlString, parameters: parameters, progress: nil, success: { (_, responseObject) in
                success(responseObject)
                }, failure: { (_, error) in
                    failure(error)
            })
        }else {
            // post 请求
            post(urlString, parameters: parameters, progress: nil, success: { (_, responseObject) in
                success(responseObject)
                }, failure: { (_, error) in
                    failure(error)
            })
        }
        
    }
}
// MARK: - 首页相关接口
extension SLNetworkTools {
    // 请求天气接口
    func loadWeather(name: String, success:@escaping (Any?)->(), failure:@escaping (Error)->()){
        // 请求 url
        let urlString = "http://www.weather.com.cn/data/sk/101010100.html"
        // 请求参数
//        let dict = ["name": name]
        // 发送请求
        requet(method: SLNetworkToolsMethod.get, urlString: urlString, parameters: nil, success: success, failure: failure)
    }
}
